<template>
<section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="filters">
            <el-form-item>
                <el-input v-model="filters.userName" placeholder="医生姓名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="filters.department" placeholder="所属科室"></el-input>
            </el-form-item>
            <el-form-item>
                <el-date-picker type="date" placeholder="选择日期" v-model="filters.registeredDate" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" v-on:click="queryRegisteredList">查询</el-button>
            </el-form-item>
            <div id="divform"></div>
        </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="dataList" highlight-current-row v-loading="listLoading" style="width: 100%;">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="userName" label="医生姓名" sortable></el-table-column>
        <el-table-column prop="department" label="所属科室" sortable></el-table-column>
        <el-table-column prop="title" label="职称" sortable></el-table-column>
        <el-table-column prop="registeredFee" label="挂号费" sortable></el-table-column>
        <el-table-column prop="registeredCount" label="今日剩余" sortable></el-table-column>
        <el-table-column label="操作" width="200">
            <template slot-scope="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">挂号</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
        <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="size" :total="total" style="float:right;"></el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
        <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
            <el-form-item label="就诊记录" prop="haveAccount">
                <el-radio-group v-model="editForm.haveAccount">
                    <el-radio class="radio" :label="'1'">有</el-radio>
                    <el-radio class="radio" :label="'0'">无</el-radio>
                </el-radio-group>
            </el-form-item>
            <!--fetch-suggestions是输入框一获取焦点。就会自动调用该方法拿到数据，这些数据就是输入建议的数据-->
            <!--@select="handleSelect"是选中某一项时调用这个方法-->
            <el-form-item label="病人姓名" prop="userName" v-if="editForm.haveAccount == '1'">
                <el-autocomplete v-model="editForm.userName" style="width:100%;" :fetch-suggestions="queryUser" @select="handleSelect"></el-autocomplete>
            </el-form-item>
            <el-form-item label="病人姓名" prop="userName" v-if="editForm.haveAccount == '0'">
                <el-input v-model="editForm.userName"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="editForm.sex">
                    <el-radio class="radio" :label="'1'">男</el-radio>
                    <el-radio class="radio" :label="'0'">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="预留电话" prop="phoneNumber">
                <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="identity">
                <el-input v-model="editForm.identity" @blur="calculateAge"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input v-model="editForm.age"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
        </div>
    </el-dialog>
</section>
</template>

<script>
import {
    mapGetters
} from "vuex";
import * as api from "@/api/api.js";
import {
    parse
} from "path";
import axios from "axios";
const Qs = require('qs');

export default {
    data() {
        return {
            defaultProps: {
                children: "children",
                label: "nodeName"
            },
            filters: {
                userName: "",
                department: "",
                registeredDate: null
            },
            showUrl: api.showUrl,
            uploadFileUrl: api.uploadFileUrl,
            dataList: [],
            total: 0,
            current: 1,
            size: 10,
            listLoading: false,
            sels: [], //列表选中列
            editFormVisible: false, //编辑界面是否显示
            editLoading: false,
            editFormRules: {
                userName: [{ required: true, message: "请填写", trigger: "blur" }],
                age: [{ required: true, message: "请填写", trigger: "blur" }],
                sex: [{ required: true, message: "请填写", trigger: "blur" }],
                phoneNumber: [{ required: true, message: "请填写", trigger: "blur" }],
                identity: [{ required: true, message: "请填写", trigger: "blur" }],
            },
            //编辑界面数据
            editForm: {
                haveAccount: '0'
            },
            nucleicAcidStatus: "无记录"
        };
    },
    computed: {
        ...mapGetters("user", ["getUser"])
    },
    methods: {
        handleCurrentChange(val) {
            this.current = val;
            this.queryRegisteredList();
        },
        //获取列表
        queryRegisteredList() {
            let para = {
                current: this.current,
                size: this.size,
                userName: this.filters.userName,
                department: this.filters.department,
                registeredDate: this.filters.registeredDate,
            };
            this.listLoading = true;
            api.queryRegisteredList(para)
                .then(res => {
                    this.total = res.returnPage.total;
                    this.dataList = res.returnPage.records;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm("确认删除该记录吗?", "提示", {
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    let para = {
                        userId: row.userId
                    };
                    api.delRegistered(para).then(res => {
                        this.listLoading = false;
                        if (res.message == 'success') {
                            this.$message({
                                message: "删除成功",
                                type: "success"
                            });
                        }
                        this.queryRegisteredList();
                    });
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true;
            this.editForm = Object.assign({}, { //将源对象(source)的所有可枚举属性,复制到目标对象(target)
                haveAccount: '0',
                doctorId: row.doctorId,
                registeredFee: row.registeredFee,
                registeredId: row.registeredId,
                doctorName: row.userName,
                department: row.department
            });
        },
        //显示新增界面
        handleAdd: function () {
            this.editFormVisible = true;
            this.editForm = {};
        },
        //编辑 表单
        editSubmit: function () {
            this.$refs.editForm.validate(valid => { //ref 绑定控件，$refs 获取控件。表单验证的方法，valid 是validate方法的回调参数 代表是否通过验证
                if (valid) {
                    this.nucleicAcidStatus = "无记录";
                    //查他是否有核酸记录
                    api.queryNucleicAcidByPage({ current: 1, size: 99999, userId: this.editForm.userId ? this.editForm.userId : "al" }).then(res => {
                        this.nucleicAcidStatus = res.returnPage.records && res.returnPage.records[0] ? res.returnPage.records[0].testStatus : this.nucleicAcidStatus;
                        this.$confirm(this.nucleicAcidStatus == "正常" ? "确认提交吗？" : "无核酸检测记录或已过期，确认提交吗？", "提示", {}).then(() => {
                            let para = Object.assign({}, this.editForm); //将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
                            if (this.filters.registeredDate) {
                                para.registeredDate = this.filters.registeredDate;
                            }
                            para.createUser = this.getUser.userId;

                            if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(para.identity)) {
                                this.$message({ message: "身份证号格式不正确", type: "warning" });
                                this.editLoading = false;
                                return;
                            }
                            if (!/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/.test(para.phoneNumber)) {
                                this.$message({ message: "手机号码格式不正确", type: "warning" });
                                this.editLoading = false;
                                return;
                            }

                            api.addRegistered(para)
                                .then(res => {
                                    this.editLoading = false;
                                    if (res.message == 'success') {
                                        this.$message({
                                            message: "挂号成功",
                                            type: "success"
                                        });
                                        this.$refs["editForm"].resetFields(); //关闭表单清空内容
                                        this.editFormVisible = false;
                                        //付款界面
                                        this.pay(para, res.returnObj);
                                        // this.queryRegisteredList();
                                    }
                                })
                                .catch(() => {
                                    this.listLoading = false;
                                });
                        });
                    }).catch(() => {});

                }
            });
        },
        queryUser(queryString, callback) {
            let para = {
                userType: '3',
                userName: queryString
            };
            api.queryUser(para)
                .then(res => {
                    let list = res.returnList.map(item => {
                        item.value = item.userName
                        return item;
                    });
                    callback(list);
                }).catch(() => {});
        },
        handleSelect(item, index) {
            this.editForm.userId = item.userId;
            this.editForm.userName = item.userName;
            this.editForm.sex = item.sex;
            this.editForm.age = item.age;
            this.editForm.phoneNumber = item.phoneNumber;
            this.editForm.identity = item.identity;
        },
        pay(para, registered) {
            axios.post(
                    api.url + "/alipay/payment",
                    Qs.stringify({ //qs是npm仓库管理的包，Qs.stringify是进行序列化
                        orderId: registered.registeredId,
                        subject: para.userName + "的挂号费",
                        body: "挂号费用,医生姓名:" + para.doctorName + ",所属科室:" + para.department,
                        money: para.registeredFee,
                    }), {
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded", //通过POST方式以页面表单方式提交数据到接口
                        },
                    }
                )
                .then((res) => {
                    let divForm = document.getElementById("divform");
                    if (divForm.length) {
                        document.body.removeChild(divForm[0]);
                    }
                    const div = document.createElement("divform");
                    div.innerHTML = res.data;
                    document.body.appendChild(div);
                    document.getElementsByName("punchout_form")[0].submit();
                })
                .catch((error, status) => {
                    console.log(error);
                });
        },
        queryNucleicAcidByPage(userId) {
            let para = { current: 1, size: 99999, userId: userId };
            api.queryNucleicAcidByPage(para)
                .then(res => {
                    if (res.returnPage.records && res.returnPage.records[0]) {
                        this.nucleicAcidStatus = res.returnPage.records[0].testStatus;
                    }
                }).catch(() => {});
        },
        calculateAge() {
            if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(this.editForm.identity)) {
                this.$message({ message: "身份证号格式不正确", type: "warning" });
                return;
            } else {
                var yearBirth = this.editForm.identity.substring(6, 10);
                var monthBirth = this.editForm.identity.substring(10, 12);
                var dayBirth = this.editForm.identity.substring(12, 14);
                //获取当前年月日并计算年龄
                var myDate = new Date();
                var monthNow = myDate.getMonth() + 1;
                var dayNow = myDate.getDay();
                var age = myDate.getFullYear() - yearBirth;
                if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
                    age--;
                }
                // alert(age);
                //得到年龄
                this.$set(this.editForm,"age",age);
            }
        }
    },
    mounted() {
        this.queryRegisteredList();
    }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.file {
    position: relative;
    display: inline-block;
    background: #63E0EC;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #FFFFFF;
    text-decoration: none;
    text-indent: 0;
    line-height: 30px;
    height: 30px;
}

.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}

.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}
</style>
